<template>
  <v-app>
    <v-container fluid>
      <v-row>
        <v-spacer></v-spacer>
        <v-col>
          <v-card>
            <v-card-title primary-title>Login</v-card-title>
            <v-card-text>
              <v-form ref>
                <v-text-field
                  name="name"
                  label="name"
                  id="id"
                  v-model="username"
                ></v-text-field>
                <v-text-field
                  name="name"
                  label="label"
                  id="id"
                  v-model="password"
                ></v-text-field>
                <v-btn class="mr-2" color="primary" @click="login">login</v-btn>
                <v-btn color="primary" @click="jwt">jwt</v-btn>
              </v-form>
            </v-card-text>
          </v-card>
        </v-col>
        <v-spacer></v-spacer>
      </v-row>
    </v-container>
  </v-app>
</template>
<style></style>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import router from "../router";

@Component({})
export default class Login extends Vue {
  backendBase = "http://localhost:3000/";
  username = "";
  password = "";
  login() {
    console.log(this.username + this.password);
    this.axios
      .post(this.backendBase + "login", {
        name: this.username,
        password: this.password
      })
      .then(res => {
        console.log(res.data);
        if (res.data.msg == "validation succeed") {
          localStorage.setItem("currentUser", res.data.token);
          this.$router.push("/dashboard/" + res.data.name);
        }
      });
  }
  jwt() {
    this.axios
      .get(this.backendBase + "login/dashboard", {
        headers: {
          Authorization: "Bearer " + localStorage.getItem("currentUser")
        }
      })
      .then(res => {
        if (!res.data.error) {
          console.log(res.data);
          this.$router.push("/dashboard/" + res.data.name);
        }
      });
  }
  beforeCreate() {
    const currentUser = localStorage.getItem("currentUser");
    console.log(currentUser);
    if (currentUser != null) {
      this.axios
        .get("http://localhost:3000/login/dashboard", {
          headers: {
            Authorization: "Bearer " + currentUser
          }
        })
        .then(res => {
          if (!res.data.error) {
            console.log(res.data);
            this.$router.push(`/dashboard/${res.data.name}`);
          }
        });
    }
  }
}
</script>
